<template>
  <div class="electricity" ref="Electricity"></div>
</template>
<script>
import * as echarts from 'echarts';
import { getElectricity } from '@/api/home/home'
import monent from 'moment'
export default {
  name: 'Electricity',
  props: {
    date: {
      type: [ Number, Date],
      required: true
    }
  },
  data() {
    return {
      chartDom: null,
      option: {}
    }
  },
  computed: {
    formatDate() {
      return monent(this.date).format('yyyy-MM-DD')
    }
  },
  mounted() {
    this.init()
    window.addEventListener('resize', this.resize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resize)
  },
  watch: {
    date: {
      handler(val) {
        this.getData()
      }
    }
  },
  methods: {
    getData() {
      getElectricity({ date: this.formatDate }).then(response => {
        response.data.map((item,index) => {
          this.option.xAxis.data[index] = item.hour
          this.option.series[0].data[index] = item.count
        })
        this.chartDom.setOption(this.option)
      })
    },
    init() {
      this.chartDom = echarts.init(this.$refs.Electricity)
      this.option = {
        grid: {
          top: '40px',
          left: '30px',
          bottom: '60px',
          right: '0'
        },
        xAxis: {
          type: 'category',
          data: [],
          axisTick: {
            show: false
          },
          axisLine: {
            lineStyle: {
              color: "#162436"
            }
          },
          axisLabel: {
            textStyle: {
              color: '#8A99A6',
              fontSize: '0.875rem'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '(度)',
          nameTextStyle: {
            color: '#FFFFFF',
            padding: [0, '30', 0, '0'],
            fontSize: '0.875rem'
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed',
              color: "#AAD1E310"
            }
          },
          axisLabel: {
            textStyle: {
              color: '#8A99A6',
              fontSize: '0.875rem'
            }
          }
        },
        series: [
          {
            data: [],
            type: 'bar',
            barWidth: '10px',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                {
                  offset: 0,
                  color: 'rgba(80,176,181,0)'
                },
                {
                  offset: 1,
                  color: 'rgba(80,176,181,100%)'
                }
            ])
            }
          }
        ]
      }
      // this.chartDom.setOption(this.option)
      this.getData()
    },
    resize() {
      this.chartDom.resize()
    },
  }
}
</script>
<style lang="scss" scoped>
.electricity {
  width: 100%;
  height: 16.333333333333332rem;
}
</style>